package com.xmutca.sso.provider.manager;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.xmutca.core.common.Paging;
import com.xmutca.core.common.Receipt;
import com.xmutca.core.common.Result;
import com.xmutca.core.common.Results;
import com.xmutca.sso.api.Permission;
import com.xmutca.sso.api.manager.service.PermissionService;
import com.xmutca.sso.dao.PermissionDao;
import com.xmutca.sso.dao.RolePermissionDao;
import com.xmutca.sso.dao.UserPermissionDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Map;

/**
 * @author: 彭伟煌(pengweihuang@xmutca.com)
 * @create: 2016-08-29 17:43
 */
@Service(version = "1.0.0", group = "sso", mock = "true")
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    @Autowired
    private UserPermissionDao userPermissionDao;

    @Override
    public Receipt add(Permission permission) {
        permissionDao.add(permission);
        return new Receipt(Receipt.Status.SUCCESS);
    }

    @Override
    @Transactional
    public Receipt del(Integer id) {
        rolePermissionDao.delByPermission(id);//删除角色权限
        userPermissionDao.delByPermission(id);//删除用户权限
        permissionDao.updateState(Permission.STATE_UNABLE, id);//更新状态
        return new Receipt(Receipt.Status.SUCCESS);
    }

    @Override
    @Transactional
    public Receipt batchDel(List<Integer> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            rolePermissionDao.batchDelByPermissions(ids);
            userPermissionDao.batchDelByPermissions(ids);
            permissionDao.batchUpdateState(Permission.STATE_UNABLE, ids);
        }
        return new Receipt(Receipt.Status.SUCCESS);
    }

    @Override
    public Receipt update(Permission permission) {
        permissionDao.update(permission);
        return new Receipt(Receipt.Status.SUCCESS);
    }

    @Override
    public Results<Permission> query(@Min(value = 1, message = "页数最小为1") int current, @Max(value = 50, message = "条数最大为50条") int pageSize, Map<String, Object> paramMap) {
        int count = permissionDao.countQuery(paramMap);
        paramMap.put("startRow", (current - 1) * pageSize);
        paramMap.put("pageSize", pageSize);
        List<Permission> roles = permissionDao.query(paramMap);
        return new Results<>(Results.Status.SUCCESS, roles, new Paging(current, pageSize, count));
    }
}
